import { Injectable, Compiler } from '@angular/core';
import { ExtendModule } from '../models/module';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { CommonModuleInfo } from '../models/common-module-info';
import { HttpHeaders, HttpClient } from '@angular/common/http';

import * as AngularCore from '@angular/core';
import * as AngularCommon from '@angular/common';
import * as AngularRouter from '@angular/router';
import * as AngularForms from '@angular/forms';
import * as AngularAnimations from '@angular/animations';
import * as AngularHttp from '@angular/http';
import * as RxJS from 'rxjs';
import * as RxJSCompat from 'rxjs-compat';
import { ServerConfig } from '../models/server-config';

declare const SystemJS: any;
const commonModules: CommonModuleInfo[] = [
    { name: '@angular/core', module: AngularCore },
    { name: '@angular/common', module: AngularCommon },
    { name: '@angular/router', module: AngularRouter },
    { name: '@angular/forms', module: AngularForms },
    { name: '@angular/animations', module: AngularAnimations },
    { name: '@angular/http', module: AngularHttp },
    { name: 'rxjs', module: RxJS },
    { name: 'rxjs-compat', module: RxJSCompat }
];

@Injectable()
export class ModuleService {

    installedModules$: Observable<ExtendModule[]>;
    // serverAddress = 'http://127.0.0.1';
    serverAddress = '';
    constructor(
        private compiler: Compiler,
        private http: HttpClient
    ) { }
    /**
     * 从服务器获取可用的angular module列表
     */
    getValidModules(serverConfig?: ServerConfig): Observable<any> {
        const reqOptions: any = this.getHttpOptions();
        // const serverAddress = serverConfig ? serverConfig.serverAddress : this.serverAddress;
        // const url = `${serverAddress}/module/extendModule`;
        // 本地测试可用模块JSON信息
        const url = './assets/modules.json';
        return this.http.get(url, reqOptions);
    }
    /**
     * 使用systemJS加载指定angular module
     * @param extendModule 待加载的angular module
     */
    async loadModulesBySystemJS(extendModule: ExtendModule): Promise<any> {
        const url = `${this.serverAddress}${extendModule.packageUrl}`;
        this.setCommonModule(commonModules);
        const module = await SystemJS.import(`${url}`);
        const compiled = await this.compiler.compileModuleAndAllComponentsAsync(module[`${extendModule.codeName}`]);
        return module;
    }

    /**
     * 设置公共的模块
     * @param commonModuleInfos 公共模块数组
     */
    private setCommonModule(commonModuleInfos: CommonModuleInfo[]) {
        if (Array.isArray(commonModuleInfos) && commonModuleInfos.length) {
            commonModuleInfos.forEach(moduleInfo => {
                SystemJS.set(moduleInfo.name, SystemJS.newModule(moduleInfo.module));
            });
        }
    }

    private getHttpOptions() {
        const httpOptions = {
            headers: new HttpHeaders({
                token: '60e7e16d0bc98b7d987abedf93ae905f'
            })
        };
        return httpOptions;
    }
}
